package dao

import (
	"fmt"

	"gitee.com/shuwenhe/shuwen-mall/model"
	"gitee.com/shuwenhe/shuwen-mall/utils"
)

func GetItems() ([]*model.Item, error) {
	sql := "select id,title,author,price,sales,stock,img_path from items"
	rows, err := utils.Db.Query(sql)
	if err != nil {
		return nil, err
	}
	var books []*model.Item
	for rows.Next() {
		book := &model.Item{}
		rows.Scan(&book.ID, &book.Title, &book.Author, &book.Price, &book.Sales, &book.Stock, &book.ImgPath) // 给book中的字段赋值
		books = append(books, book)                                                                          // 将book添加到books切片中
	}
	return books, nil
}

// AddItems 向数据库添加商品
func AddItems(item *model.Item) error {
	sql := "insert into items(title,author,price,sales,stock,img_path) values(?,?,?,?,?,?)"
	_, err := utils.Db.Exec(sql, item.Title, item.Author, item.Price, item.Sales, item.Stock, item.ImgPath)
	if err != nil {
		return err
	}
	return nil
}

func DeleteItem(itemID string) error {
	sql := "delete from items where id = ?"
	_, err := utils.Db.Exec(sql, itemID)
	if err != nil {
		return err
	}
	return nil
}

func GetItemByID(itemID string) (*model.Item, error) {
	sql := "select id,title,author,price,sales,stock,img_path from items where id = ?"
	row := utils.Db.QueryRow(sql, itemID)
	item := &model.Item{}
	row.Scan(&item.ID, &item.Title, &item.Author, &item.Price, &item.Sales, &item.Stock, &item.ImgPath)
	return item, nil
}

func UpdateItem(item *model.Item) error {
	sql := "update items set title = ?,author = ?,price = ?,sales = ?,stock = ?,img_path = ? where id = ?"
	_, err := utils.Db.Exec(sql, item.Title, item.Author, item.Price, item.Sales, item.Stock, item.ImgPath, item.ID)
	if err != nil {
		fmt.Println("err = ", err)
		return err
	}
	return nil
}
